import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';

type ThemeMode = 'light' | 'dark' | 'auto';

interface ThemeState {
  mode: ThemeMode;
  primaryColor: string;
  setMode: (mode: ThemeMode) => void;
  setPrimaryColor: (color: string) => void;
  isDark: () => boolean;
}

export const useThemeStore = create<ThemeState>()(
  persist(
    (set, get) => ({
      mode: 'light',
      primaryColor: '#1890ff',

      setMode: (mode) => {
        set({ mode });
        applyTheme(mode, get().primaryColor);
      },

      setPrimaryColor: (color) => {
        set({ primaryColor: color });
        applyTheme(get().mode, color);
      },

      isDark: () => {
        const { mode } = get();
        if (mode === 'auto') {
          return window.matchMedia('(prefers-color-scheme: dark)').matches;
        }
        return mode === 'dark';
      },
    }),
    {
      name: 'theme-storage',
      storage: createJSONStorage(() => localStorage),
    },
  ),
);

// 应用主题
function applyTheme(mode: ThemeMode, primaryColor: string) {
  const isDark =
    mode === 'dark' || (mode === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches);

  document.documentElement.classList.toggle('dark', isDark);
  document.documentElement.style.setProperty('--primary-color', primaryColor);
}

// 监听系统主题变化
if (window.matchMedia) {
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
    const store = useThemeStore.getState();
    if (store.mode === 'auto') {
      document.documentElement.classList.toggle('dark', e.matches);
    }
  });
}

